package com.zmn.plat.admin.controller.product;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.KvDTO;
import com.zmn.common.utils.logger.LoggerUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.office.ExcelUtil;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.manager.dictionary.ProductDict;
import com.zmn.plat.manager.dictionary.ServProductUnitDict;
import com.zmn.plat.model.entity.category.BaseCategory;
import com.zmn.plat.model.entity.category.BaseCategoryQuery;
import com.zmn.plat.model.entity.product.*;
import com.zmn.plat.model.entity.servcategory.ServAssCategoryQuery;
import com.zmn.plat.model.entity.servcategory.ServCategory;
import com.zmn.plat.model.vo.product.ServProductVO;
import com.zmn.plat.model.vo.servcategory.BaseCategoryAttributeVO;
import com.zmn.plat.model.vo.servcategory.ServAssCategoryVO;

/**
 * 描述: 产品管理查询控制
 *
 * @author tanbiao
 * @since: 2018/11/5 22:06
 */
@Controller
@RequestMapping("/tariffProduct/")
public class TariffServProductListController extends ServProductBaseController {

    private Logger logger = LoggerFactory.getLogger(TariffServProductListController.class);

    /**
     * 描述: 前台产品列表
     *
     * @param query
     *            查询实体
     * @return ModelAndView
     * @author tanbiao
     * @since 15:38 2019/9/22
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping(value = "list")
    @RequiresPermissions("/tariffProduct/list.action")
    public ModelAndView list(@ModelAttribute ServProductQuery query) {
        // 计价器产品类型
        query.setShowType(ProductConsts.ET_PRODUCT_TYPE);
        ModelAndView mav = new ModelAndView("product/tariff/list");

        try {
            ServCategory querySC = new ServCategory();
            // 服务分类
            List<ServCategory> servCategories = servCategoryService.listByQuery(querySC);

            List<BaseCategory> baseCategories = Collections.emptyList();
            if (NumberUtil.isPositiveInteger(query.getServCategId())) {
                baseCategories =
                    servAssCategoryService.findCategoryOneByServIdAndShowType(query.getServCategId(), ProductDict.EC_PRODUCT_TYPE);
            }

            List<ServAssCategoryVO> baseCategoryTwoList = Collections.emptyList();
            if (NumberUtil.isPositiveInteger(query.getCategOneId())) {
                ServAssCategoryQuery queryBQ = new ServAssCategoryQuery();
                queryBQ.setServCategId(query.getServCategId());
                queryBQ.setCategOneId(query.getCategOneId());
                queryBQ.setShowType(ProductDict.EC_PRODUCT_TYPE);
                baseCategoryTwoList = servAssCategoryService.listByQuery(queryBQ);
            }
            // 后台产品数据
            ServProductQuery servProductQuery = new ServProductQuery();
            servProductQuery.setShowType(ProductConsts.ERP_PRODUCT_TYPE);
            List<ServProduct> backProducts = servProductService.listByQuery(servProductQuery);

            BaseCategoryQuery queryB = new BaseCategoryQuery();
            queryB.setShowType(ProductDict.EC_PRODUCT_TYPE);
            List<BaseCategory> baseCategorieall = baseCategoryService.listByQuery(queryB);

            List<ServProductVO> items = servProductBService.listTariffVOPageByQuery(query, servCategories, baseCategorieall);

            mav.addObject("items", items);
            mav.addObject("vo", query);
            mav.addObject("servCategories", servCategories);
            mav.addObject("baseCategories", baseCategories);
            mav.addObject("baseCategoryTwoList", baseCategoryTwoList);
            mav.addObject("priceTypes", GlobalDict.getPriceTypeList());
            mav.addObject("productTypes", GlobalDict.getProductTypeList());
            mav.addObject("status", GlobalDict.getMasterState());
            // 后台产品选择框
            mav.addObject("backProducts", backProducts);
            mav.addObject("bizTypeList", com.zmn.plat.common.dictionary.ProductDict.listBizType());
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mav;
    }

    /**
     * 描述: 产品添加，修改页面 跳转方法
     *
     * @param productId
     *            产品id
     * @return modelAndView
     * @author tanbiao
     * @since 15:38 2019/9/22
     */
    @RequestMapping(value = "addEditView")
    @SuppressWarnings("Duplicates")
    @RequiresPermissions("/tariffProduct/addEditView.action")
    public ModelAndView addEditView(@RequestParam(value = "productId", defaultValue = "0") Integer productId) {

        ServProduct product = productId > ProductDict.ZERO ? servProductService.findByKey(productId) : new ServProduct();
        ModelAndView modelAndView = new ModelAndView("product/tariff/detail");
        ServProductVO servProductVO = new ServProductVO();

        if (Objects.isNull(product.getProductId())) {
            // 前台产品排序默认最大值＋1
            Integer maxShowSort = servProductService.findMaxShowSort();
            product.setShowSort(maxShowSort == null ? 1 : maxShowSort + 1);
        }
        BeanUtils.copyProperties(product, servProductVO);

        ServCategory querySC = new ServCategory();
        querySC.setShowStatus(GlobalConsts.YES);
        List<ServCategory> servCategories = servCategoryService.listByQuery(querySC);
        // 是修改的情况下，需要将禁用的服务分类添加到集合中用于显示
        if (product.getProductId() != null) {
            ServCategory category = servCategoryService.findByKey(product.getServCategId());
            if (!category.getShowStatus().equals(GlobalConsts.YES)) {
                servCategories.add(category);
            }
        }

        List<KvDTO<Integer, String>> baseCategories = Collections.emptyList();
        List<ServAssCategoryVO> categoryVOList = Collections.emptyList();
        List<BaseCategoryAttributeVO> attrList = Collections.emptyList();
        List<FicoCategory> ficoCategoryList = ficoCategoryService.listAll();

        if (product.getProductId() != null) {
            ServAssCategoryQuery queryBQ = new ServAssCategoryQuery();
            queryBQ.setServCategId(product.getServCategId());
            queryBQ.setCategOneStatus(GlobalConsts.YES);
            queryBQ.setShowType(ProductConsts.EC_PRODUCT_TYPE);
            baseCategories = servAssCategoryService.listCateOneByQuery(queryBQ);

            BaseCategoryQuery baseCategoryQueryOne = new BaseCategoryQuery();
            baseCategoryQueryOne.setCategId(product.getCategOneId());
            List<BaseCategory> baseList = baseCategoryService.listByQuery(baseCategoryQueryOne);

            BaseCategory baseCategoryOne = CollectionUtils.isEmpty(baseList) ? null : baseList.get(0);
            if (baseCategoryOne != null && !baseCategoryOne.getStatus().equals(GlobalConsts.YES)) {
                baseCategories.add(new KvDTO<>(baseCategoryOne.getCategId(), baseCategoryOne.getName()));
            }

            ServAssCategoryQuery query = new ServAssCategoryQuery();
            query.setCategOneId(product.getCategOneId());
            query.setServCategId(product.getServCategId());
            query.setCategTwoStatus(GlobalConsts.YES);
            query.setShowType(ProductConsts.EC_PRODUCT_TYPE);
            categoryVOList = servAssCategoryService.listByQuery(query);

            BaseCategoryQuery baseCategoryQueryTwo = new BaseCategoryQuery();
            baseCategoryQueryTwo.setCategId(product.getCategId());
            List<BaseCategory> baseCategoryTwoList = baseCategoryService.listByQuery(baseCategoryQueryTwo);
            BaseCategory baseCategoryTwo = CollectionUtils.isEmpty(baseCategoryTwoList) ? null : baseCategoryTwoList.get(0);
            if (baseCategoryTwo != null && !baseCategoryTwo.getStatus().equals(GlobalConsts.YES)) {
                ServAssCategoryVO vo = new ServAssCategoryVO();
                vo.setCategId(baseCategoryTwo.getCategId());
                vo.setCategName(baseCategoryTwo.getName());
                categoryVOList.add(vo);
            }
            if (NumberUtil.isPositiveInteger(product.getCategOneId()) && NumberUtil.isPositiveInteger(product.getCategId())) {
                attrList = servProductBService.findAttrById(product.getCategOneId(), product.getCategId(), product.getChannelId());
            }
        }

        ServSubsidiaryGroupQuery subQuery = new ServSubsidiaryGroupQuery();
        subQuery.setType(ProductConsts.SERV_SUB_TYPE_HITCH);
        subQuery.setStatus(GlobalConsts.YES);
        List<ServSubsidiaryGroup> faults = servSubsidiaryGroupService.listByQuery(subQuery);

        subQuery.setType(ProductConsts.SERV_SUB_TYPE_GUARANTEE);
        List<ServSubsidiaryGroup> warrantys = servSubsidiaryGroupService.listByQuery(subQuery);

        modelAndView.addObject("priceStatement", product.getPriceStatement());
        modelAndView.addObject("attrList", attrList);
        modelAndView.addObject("ficoCategoryList", ficoCategoryList);
        modelAndView.addObject("servProductVO", servProductVO);
        modelAndView.addObject("servCategories", servCategories);
        modelAndView.addObject("baseCategories", baseCategories);
        modelAndView.addObject("categoryVOList", categoryVOList);
        modelAndView.addObject("faults", faults);
        modelAndView.addObject("warrantys", warrantys);
        List<String> unitList = listAllUnitName();
        modelAndView.addObject("unitList", unitList);
        modelAndView.addObject("flag", 1);
        modelAndView.addObject("bizTypeList", com.zmn.plat.common.dictionary.ProductDict.listBizType());

        return modelAndView;
    }

    /**
     * 描述: 产品添加，修改页面 跳转方法
     *
     * @param productId
     *            产品id
     * @return modelAndView
     * @author tanbiao
     * @since 15:38 2019/9/22
     */
    @RequestMapping(value = "editDescView")
    @RequiresPermissions("/tariffProduct/editDescView.action")
    public ModelAndView editDescView(@RequestParam(value = "productId", defaultValue = "0") Integer productId) {

        ServProduct product = productId > ProductDict.ZERO ? servProductService.findByKey(productId) : new ServProduct();
        ModelAndView modelAndView = new ModelAndView("product/tariff/productdesc");
        ServProductVO servProductVO = new ServProductVO();

        BeanUtils.copyProperties(product, servProductVO);

        modelAndView.addObject("servProductVO", servProductVO);
        modelAndView.addObject("flag", 2);
        return modelAndView;
    }

    /**
     * 描述: 根据条件导出工程师Excel
     *
     * @param query
     *            查询条件
     * @author wangjie
     * @since 11:43 2019/2/19
     **/
    @RequestMapping(value = "outputExcel")
    @RequiresPermissions("/tariffProduct/outputExcel.action")
    public void outputExcel(HttpServletResponse response, ServProductQuery query) {

        // 前端产品类型
        query.setShowType(ProductConsts.ET_PRODUCT_TYPE);
        query.setPageSize(getExportPageLimit(response));

        ArrayList<List> lists = servProductBService.outputTariffProductExcel(query);
        try {
            String name = "计价器产品报表.xlsx";
            name = new String(name.getBytes(), "ISO8859-1");
            ExcelUtil.export(response, lists, name, "sheet");
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "导出报表出错" + e.getMessage(), e);
        }
    }

}
